﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using System.IO;
using System.Collections.Generic;

/// <summary>
/// 订单导入
/// </summary>
public partial class qy_54tss_Admin_Shop_orderimport : System.Web.UI.Page
{
    Custorder dal = new Custorder();

    protected void Page_Load(object sender, EventArgs e)
    {
        ValidatorSet validator = new ValidatorSet("Admin");
        validator.SetValidator();
        if (!this.Page.IsPostBack)
        {
            int tid = HjNetHelper.GetQueryInt("tid", 0);
            hidTogoId.Value = tid.ToString();
        }
    }

    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void in_Click(object sender, EventArgs e)
    {
        string suffix = Path.GetExtension(this.fuFoodExcel.PostedFile.FileName).ToLower();
        string filepath = "~/upload/excel/";
        if (!System.IO.Directory.Exists(Server.MapPath(filepath)))
        {
            System.IO.Directory.CreateDirectory(Server.MapPath(filepath));
        }
        string sFile = filepath + System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + suffix;  //上传后文件的新名

        if (suffix == ".xls" || suffix == ".xlsx")
        {

            this.fuFoodExcel.PostedFile.SaveAs(Server.MapPath(sFile));

            //1.添加菜品(检查分类，没有分类就先添加分类(这个地方可比较可以少查询次数))
            int index = 0;
            //必要的判断以防止excel格式的问题导致程序错误
            try
            {
                //解析文件并保存数据到数据库

                EAdminInfo user = UserHelp.GetAdmin();

                System.Data.DataTable chooseDt = ExcelHelper.ExcelToDataTable(Server.MapPath(sFile), 0);//选中文件DataTable


                IList<ShopDataInfo> ids = new Points().getShopIDs(" cityid=" + user.CityID);
                foreach (DataRow item in chooseDt.Rows)
                {
                    index++;
                    bool good = false;

                    string togoid = item[0].ToString().Trim();
                    if (togoid.Length == 0)
                    {
                        break;
                    }


                    int togoid_int = Convert.ToInt32(togoid);
                    foreach (ShopDataInfo id in ids)
                    {
                        if (id.Status == togoid_int)
                        {
                            good = true;
                        }
                    }

                    if (!good)
                    {
                        AlertScript.RegScript(this, "alert('批量失败，第" + index + "行的商家不是本站商家，请确认是否输入错误');hideload_super('tbinfood');");//
                        return;
                    }

                }

                index = 0;

                foreach (DataRow item in chooseDt.Rows)
                {
                    CustorderInfo info = new CustorderInfo();
                    info.InUse = "";
                    string togoid = item[0].ToString().Trim();

                   

                    if (togoid.Length == 0)
                    {
                        break;
                    }
                    info.TogoId = Convert.ToInt32(togoid);

                    string OrderDateTime = item[2].ToString().Trim();


                    info.OrderDateTime = OrderDateTime.Length == 0 ? Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:00")) : Convert.ToDateTime(OrderDateTime + " 23:59:00");
                    info.OrderChecker = 0;
                    info.OrderStatus = 3;

                    string OrderRcver = item[3].ToString().Trim();
                    if (OrderRcver.Length == 0)
                    {
                        OrderRcver = "AAA";
                    }

                    info.OrderRcver = OrderRcver;
                    info.OrderComm = item[4].ToString().Trim();
                    info.OrderAddress = user.AdminName;
                    info.AddressText = item[5].ToString().Trim();
                    info.OrderAddrEx = "";
                    info.OrderAttach = item[13].ToString().Trim();

                    string OrderSums = item[6].ToString().Trim();
                    if (OrderSums.Length == 0)
                    {
                        OrderSums = "0";
                    }

                    info.OrderSums = Convert.ToDecimal(OrderSums);
                    info.Sender = "";
                    info.SendTime = info.OrderDateTime;
                    info.CallPhoneNo = "";
                    info.P2Sign = "";
                    string SendFee = item[7].ToString().Trim();
                    if (SendFee.Length == 0)
                    {
                        SendFee = "0";
                    }
                    info.SendFee = Convert.ToDecimal(SendFee);
                    info.paymode = 4;
                    info.paytime = Convert.ToDateTime("1970-1-1");
                    info.paymoney = 0;
                    info.paystate = 0;
                    info.SetStateTime = DateTime.Now;
                    info.UserId = 0;

                    info.orderid = HjNetHelper.GetTime() + index.ToString("0000");
                    info.fromweb = "9";
                    info.OldStatus = 100;

                    string SystemUserId = item[12].ToString().Trim();
                    if (SystemUserId == "是")
                    {
                        SystemUserId = "1";
                    }
                    else
                    {
                        SystemUserId = "0";
                    }

                    info.SystemUserId = Convert.ToInt32(SystemUserId);
                    info.Commentstate = 0;
                    info.writer = user.AdminName;
                    info.IsShopSet = 1;
                    info.cityid = 0;
                    info.deliversiteid = 0;
                    info.deliverheaderid = 0;
                    string deliverid = item[9].ToString().Trim();
                    if (deliverid.Length == 0)
                    {
                        deliverid = "0";
                    }
                    info.deliverid = Convert.ToInt32(deliverid);
                    info.sendstate = 3;
                    info.ReveInt1 = 0;
                    info.ReveInt2 = 0;
                    info.ReveVar1 = "1";
                    info.ReveVar2 = "{'ulat':'0','ulng':'0','slat':'0','slng':'0'}";
                    info.ReveDate1 = DateTime.Now;
                    info.ReveDate2 = DateTime.Now;
                    info.OldPrice = 0;

                    string shopdiscountmoney = item[7].ToString().Trim();
                    if (shopdiscountmoney.Length == 0)
                    {
                        shopdiscountmoney = "0";
                    }

                    info.shopdiscountmoney = Convert.ToDecimal(shopdiscountmoney);
                    info.tempcode = "";

                    string cardpay = item[10].ToString().Trim();
                    if (cardpay.Length == 0)
                    {
                        cardpay = "0";
                    }

                    info.cardpay = Convert.ToDecimal(cardpay);
                    info.cardids = item[14].ToString().Trim();
                    info.pointrat = 0;
                    info.Packagefee = 0;
                    info.settleuser = "";
                    info.isauth = 0;
                    info.isfile = 0;
                    info.Commission = 0;
                    info.settlecycle = 0;

                    string Advance = item[8].ToString().Trim();
                    if (Advance.Length == 0)
                    {
                        Advance = "0";
                    }
                    info.Advance = Convert.ToDecimal(Advance);
                    info.Mergeorderremark = item[11].ToString().Trim();
                    info.delflag = 0;
                    info.deluser = "";
                    info.deltime = Convert.ToDateTime("1970-1-1");
                    info.shopauthuser = "";
                    info.shopfileuser = "";

                    //todo 分钟都是小数点后的两两位
                    string timeout = item[15].ToString().Trim();
                    if (timeout.Length == 0)
                    {
                        timeout = "0";
                    }

                    info.ReveInt1 = Convert.ToInt32(Convert.ToDecimal(timeout));
                    info.deliversiteid = 0;

                    if (info.ReveInt1 > 60)
                    {
                        info.deliversiteid = 10;
                    }


                    string foodmsg = item[1].ToString().Trim();

                    Points togo = new Points();
                    PointsInfo togomodel = togo.GetModel(info.TogoId);

                    decimal delivergetfee = 0;

                    info.delivergetfee_base = Convert.ToInt32(item[16].ToString().Trim());


                    //新的规则只是基数，收入=基数*比例
                    if (Convert.ToInt32(togomodel.MgrCell.ToString()) > 0) //商家比例，不为0，就按商家
                    {
                        delivergetfee = info.delivergetfee_base * Convert.ToDecimal(togomodel.MgrCell) / 100;
                    }
                    else
                    {
                        delivergetfee = 0;// 使用配送员的比例时，这里直接是0
                    }
                    info.DeliverGetSendFee = delivergetfee;
                    dal.Add(info);

                    if (info.DeliverGetSendFee == 0)
                    {
                        new Custorder().curDeliverGetSendFee(info.orderid);
                    }

                    index++;

                }
            }
            catch (Exception ex)
            {
                AlertScript.RegScript(this, "alert('已经导入" + index + "条记录，但出现错，请检查请excel文件');hideload_super();");//

                Hangjing.AppLog.AppLog.Error("导入出错：" + ex.ToString());
                return;
            }
            AlertScript.RegScript(this, "alert('批量导入成功');hideload_super('tbinfood');");//
        }
        else
        {
            AlertScript.RegScript(this, "alert('文件格式不正确，请上传excel文件!');hideload_super('tbinfood');");
        }
    }

}
